package com.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{

	private InputStream in;
	private OutputStream out;
	private PrintStream print;
	
	private final static String WEB_ROOT = "D:/server/";
	
	public Processor(Socket socket) {
		super();
		try {
			
			this.in = socket.getInputStream();
			this.out = socket.getOutputStream();
			this.print = new PrintStream(this.out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		
		String fileName = this.parseRequest(this.in);
		this.returnResult(fileName);
		
		super.run();
	}
	
	public String parseRequest(InputStream in){
		String fileName = null;
		
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		
		try {
			
			String httpMessage = br.readLine();
			String[] content = httpMessage.split(" ");
			
			if(content.length == 3){
				
				fileName = content[1];
			}
			else{
				
				this.returnErrorMessage(400,"客户端请求错误！");
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return fileName;
	}
	
	public void returnResult(String fileName){
		
		File file = new File(Processor.WEB_ROOT + fileName);
		
		if(file.exists()){
			
			InputStream fileIn = null;
			
			try {
				fileIn = new FileInputStream(file);
				byte[] content = new byte[(int)file.length()];
				fileIn.read(content);
				
				this.print.println("HTTP/1.0 200  请求文件");
				this.print.println("content-lenth:"+file.length());
				this.print.println();
				this.print.write(content);
				
				this.print.flush();
				this.print.close();
				this.out.flush();
				this.out.close();
				this.in.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else{
			
			this.returnErrorMessage(404, "请求的路径未找到");
		}
	}
	
	public void returnErrorMessage(int errorCode,String errorMessage){
		
		this.print.println("HTTP/1.0 " + errorCode + " " + errorMessage);
		this.print.println("content-type: text/html");
		this.print.println();
		this.print.println("<html>");
		this.print.println("<head>");
		this.print.println("<title>Error Message Page</title>");
		this.print.println("</head>");
		this.print.println("<body>");
		this.print.println("<h1>ErrorCode:" + errorCode + ",ErrorMessage:" + errorMessage + "</h1>");
		this.print.println("</body>");
		this.print.println("</html>");
		
		this.print.flush();
		this.print.close();
		try {
			this.out.flush();
			this.out.close();
			this.in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}

